<!-- 自定义计数器组件 用于计数器合计 -->
<template>
  <el-input-number
    ref="inputNumberRef"
    v-bind="attrs"
    :model-value="modelValue"
    @update:model-value="handleValueChange"
  />
</template>

<script setup lang="ts">
defineOptions({
  name: 'InputNumberGroupItem',
  inheritAttrs: false
})

const props = defineProps({
  modelValue: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits(['update:modelValue'])
const attrs = useAttrs()
const inputNumberRef = ref()

// 从父组件获取注册方法
const inputNumberGroup: any = inject('inputNumberGroup', null)
const updateFn = ref<Function | null>(null)
const id = ref<string>(`input-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`)

const handleValueChange = (value: number) => {
  emit('update:modelValue', value)

  // 通知父组件值已更改
  if (updateFn.value) {
    updateFn.value(value)
  }
}

onMounted(() => {
  // 注册到父组件
  if (inputNumberGroup) {
    updateFn.value = inputNumberGroup.registerChild(id.value, props.modelValue)
    updateFn.value && updateFn.value(props.modelValue)
  }
})

onUnmounted(() => {
  // 将值设为0，从总计中移除
  if (updateFn.value) {
    updateFn.value(0)
  }
})
</script>
